<?php

namespace App\Http\Controllers\Manager;

use App\Helper;
use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\Character;
use App\Models\Game\creature_template;
use App\Models\Game\creature_template_locale;
use App\Models\Game\item_template;
use App\Models\Player;
use App\Models\Server;
use App\Models\Video;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Exception;
use Illuminate\Support\Facades\DB;

class GameEditorController extends Controller
{
    public static $loca='zhCN';

    public $prefix='manager.gameEditor';
    /**
     * @param $id
     * @return mixed
     * @throws Exception
     */
//    protected function CheckServer($id){
//        $server=Server::find($id);
//        $uid=Auth::user()->id;
//        if ($server->user_id==$uid){
//            return $server;
//        }else{
//            throw new Exception('无权访问次服务器',401);
//        }
//    }
    public function index(Server $server){
        Helper::setDataBaseConf('mysql_world',$server,'acore_world');
        $item=item_template::find(44);
        return view($this->prefix.'.index',compact('item'));
//        dd($item);
    }
    public function itemList(Request $request,Server $server){
        Helper::setDataBaseConf('mysql_world',$server,'acore_world');
        $size=$request->get('size',10);
//        $list=item_template::where('entry','>',0);
        $list=item_template::leftJoin('item_template_locale as l','l.ID','=','item_template.entry')
            ->where(function ($query) {
                $query->where('l.locale', '=',  config('conf.loca'))
                    ->orWhere('l.locale', null);
            })
            ->select(['item_template.*','l.Name as name_cn']);

        $entry=$request->get('entry');
        if (!empty($entry)){
            $list=$list->where('item_template.entry',$entry);
        }
        $key=$request->get('key');
        if (!empty($key)){
            $list=$list->where(function ($query)use($key) {
                $query->where('item_template.name','like',"%$key%")
                    ->orWhere('l.Name','like',"%$key%");
            });
        }
        $quality=$request->get('quality');
        if (strlen($quality)>0){
            $list=$list->where('item_template.Quality',$quality);
        }

        if ($request->has('class')){
            $class=explode('_',$request->get('class')[1]);
            $list=$list->where('item_template.class',$class[0]);
            if (strlen($class[1])>0)
                $list=$list->where('item_template.subclass',$class[1]);
        }

        $list=$list->paginate($size);

        return JsonResponse::create(['err'=>0,'res'=>1,'data'=>$list]);
    }

    public function itemSave(Request $request,Server $server){
        Helper::setDataBaseConf('mysql_world',$server,'acore_world');
        $data=$request->all();
        if ($data['description']==null) {
            $data['description']='';
        }
        $item=item_template::find($data['entry']);
        $item->fill($data);
        $item->save();
        DB::connection('mysql_world')->delete(
            'delete from `item_template_locale` where ID=? and locale=?', [$data['entry'],self::$loca]);
        DB::connection('mysql_world')->insert(
            'INSERT INTO `item_template_locale` (ID,locale,Name,Description) VALUES (?, ?, ?, ?);',
            [$data['entry'],self::$loca,$item->name,$item->description,$data['entry'],self::$loca,$item->name,$item->description]);
        return JsonResponse::create(['err'=>0,'res'=>1,'data'=>$item]);
    }

    public function creatureList(Request $request,Server $server){
        Helper::setDataBaseConf('mysql_world',$server,'acore_world');
        $size=$request->get('size',10);
        $list=creature_template::join('creature_template_locale as l','l.entry','=','creature_template.entry')->where('l.locale','=',self::$loca)->select(['creature_template.*','l.Name as name_cn']);

        $entry=$request->get('entry');
        if (!empty($entry)){
            $list=$list->where('creature_template.entry',$entry);
        }
        $name=$request->get('name');
        if (!empty($name)){
//            Helper::setDataBaseConf('mysql_world',$server,'acore_world');
//            $ctl=creature_template_locale::where('Name',$name)->first();
            $ctl=DB::connection('mysql_world')->select("select * from creature_template_locale where Name = ?",[$name]);
            if ($ctl){
                $list=$list->where('creature_template.entry',$ctl[0]->entry);
            }else{
                $list=$list->where('creature_template.entry',0);
            }
        }


        $list=$list->paginate($size);

        return JsonResponse::create(['err'=>0,'res'=>1,'data'=>$list]);
    }

    public function characterList(Request $request,Server $server){
        Helper::setDataBaseConf('mysql_char',$server,'acore_characters');
        $size=$request->get('size',10);
        $list=Character::orderby('logout_time','desc');


        $name=$request->get('name');
        if (!empty($name)){
            $list=$list->where('name','like',"%$name%");
        }
        $class=$request->get('class');
        if (strlen($class)>0){
            $list=$list->where('class',$class);
        }
        $race=$request->get('race');
        if (strlen($race)>0){
            $list=$list->where('race',$race);
        }

        $account=$request->get('account');
        if (!empty($account)){
            Helper::setDataBaseConf('mysql_auth',$server,'acore_auth');
            $account=Account::where('username',strtoupper($account))->first();
            if ($account){
                $list=$list->where('account',$account->id);
            }else{
                $list=$list->where('account',0);
            }
        }
        $list=$list->paginate($size);

        Helper::setDataBaseConf('mysql_auth',$server,'acore_auth');
        foreach ($list as &$item){
            $acc=Account::find($item->account);
            $item->username=$acc?$acc->username:'';
            $item->accid=$acc?$acc->id:'';
            $item->ban=$acc?$acc->getBan():'';
        }
//        $list=creature_template::join('creature_template_locale as l','l.entry','=','creature_template.entry')->where('l.locale','=',self::$loca)->select(['creature_template.*','l.Name as name_cn']);
//        $list=$list->paginate($size);

        return JsonResponse::create(['err'=>0,'res'=>1,'data'=>$list]);
    }

    public function characterDoAct(Request $request,Server $server){
        $act=$request->get('act');
        $name=$request->get('name');
        $data=$request->get('data');

        $command="";
        switch ($act){
            case 'money':
                $command='send money '.$name.' "系统发放" "感谢支持" '.($data['money']*100*100);
                break;
            case 'item':
                $command='send items '.$name.' "系统发放" "感谢支持" '.$data['itemId'].':'.$data['itemCount'];
                break;
            case 'level':
                $command="character level $name {$data['level']}";
                break;
            case 'mute':
                $time=$data['muteMin']*60;
                $command="mute $name $time";
                break;
            case 'ban':
                $command="ban playeraccount $name {$data['muteMin']}d{$data['muteMin']}h sys";
                break;
            case 'unban':
                $command="unban playeraccount $name";
                break;
        }
        $res='';
        $err='';
        if ($command!==''){
            $server->runCommand($command,$res,$err);
        }

        return JsonResponse::create(['err'=>0,'res'=>1,'data'=>$err]);
    }

    public function isAgentChange(Request $request,Server $server){
        $id=$request->get('id');
        $is_agent=$request->get('is_agent');
        $p=Player::find($id);
        $p->is_agent=$is_agent;
        $p->save();
    }
    public function accountDoAct(Request $request,Server $server){
        $act=$request->get('act');
        $name=$request->get('name');
        $data=$request->get('data');

        $command="";
        switch ($act){
            case 'resetPwd':
                $command="account set password $name 123456 123456";
                break;
            case 'setGM':
                $command="account set gmlevel $name 3 -1";
                break;
            case 'unSetGM':
                $command="account set gmlevel $name 0 -1";
                break;
            case 'ban':
                $command="ban playeraccount $name {$data['muteMin']}d{$data['muteMin']}h sys";
                break;
            case 'unban':
                $command="unban playeraccount $name";
                break;
            case 'addScore':
                $player=Player::where('server_id',$server->id)->where('acc',$name)->first();
                $player->money+=$data['value'];
                $player->save();
                return JsonResponse::create(['err'=>0,'res'=>1,'data'=>$player]);

            case 'changeAgentMoney':
                $player=Player::where('server_id',$server->id)->where('acc',$name)->first();
                $player->money_agent+=$data['value'];
                $player->save();
                return JsonResponse::create(['err'=>0,'res'=>1,'data'=>$player]);

            case 'changeRecommendRatio':
                $player=Player::where('server_id',$server->id)->where('acc',$name)->first();
                $player->recommend_ratio=$data['value'];
                $player->save();
                return JsonResponse::create(['err'=>0,'res'=>1,'data'=>$player]);
                break;
        }
        $res='';
        $err='';
        if ($command!==''){
            $server->runCommand($command,$res,$err);
        }

        return JsonResponse::create(['err'=>0,'res'=>1,'data'=>$err]);
    }

    public function accountList(Request $request,Server $server){
        Helper::setDataBaseConf('mysql_auth',$server,'acore_auth');
        $size=$request->get('size',10);
        $list=Account::select(['id','username','last_login','online','expansion','totaltime'])->orderby('last_login','desc');

        $name=$request->get('name');
        if (!empty($name)){
            $list=$list->where('username','like',"%$name%");
        }

        $list=$list->paginate($size);
        foreach ($list as &$item){
            $item->ban=$item?$item->getBan():'';
            $item->gm=$item?$item->isGM():'';
            $player=Player::where('server_id',$server->id)->where('acc',$item->username)->first();
            $item->player=$player;
        }
        return JsonResponse::create(['err'=>0,'res'=>1,'data'=>$list]);
    }
    public function clearDatabase(Request $request,Server $server){

        Player::where('server_id',$server->id)->where('acc','<>','ADMIN')->delete();

        Helper::setDataBaseConf('mysql_auth',$server,'acore_auth');
        $list=Account::select(['username'])->get();

        foreach ($list as $item){
            if ($item->username!='ADMIN'){
                $res='';
                $err='';
                $server->runCommand("account delete $item->username",$res,$err);
            }
        }
        return JsonResponse::create(['err'=>0,'res'=>1,'data'=>$list]);
    }
}
